package com.app.studyroom.custom.spinner;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.PopupWindow;

import androidx.appcompat.widget.AppCompatTextView;

import com.app.studyroom.R;

import java.util.ArrayList;
import java.util.List;

public class SearchableSpinner extends AppCompatTextView {

    private Context context;
    private List<String> itemList = new ArrayList<>();
    private String selectedItem = "";
    private PopupWindow popupWindow;
    private ArrayAdapter<String> adapter;

    public interface OnItemSelectedListener {
        void onItemSelected(String item);
    }

    private OnItemSelectedListener listener;

    public SearchableSpinner(Context context) {
        super(context);
        init(context);
    }

    public SearchableSpinner(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    private void init(Context ctx) {
        this.context = ctx;
//        setBackgroundResource(android.R.drawable.btn_dropdown);  //下拉提示箭头
        setOnClickListener(v -> showPopup());
    }

    /**
     * 设置选项列表（可单独调用）
     */
    public void setItems(List<String> items) {
        this.itemList = items;
    }

    /**
     * 设置选中项监听器
     */
    public void setOnItemSelectedListener(OnItemSelectedListener l) {
        this.listener = l;
    }

    /**
     * 用于模拟 Spinner 的 setAdapter 行为
     */
    public void setAdapter(ArrayAdapter<String> adapter) {
        this.adapter = adapter;
        this.itemList = new ArrayList<>();
        for (int i = 0; i < adapter.getCount(); i++) {
            itemList.add(adapter.getItem(i));
        }
        if (!itemList.isEmpty()) {
            setText(itemList.get(0));
            selectedItem = itemList.get(0);
        }
    }

    /**
     * 设置默认选中项
     */
    public void setSelection(int position) {
        if (adapter != null && position >= 0 && position < adapter.getCount()) {
            selectedItem = adapter.getItem(position);
            setText(selectedItem);
            if (listener != null) listener.onItemSelected(selectedItem);
        }
    }

    /**
     * 获取选中项内容
     */
    public Object getSelectedItem() {
        return selectedItem;
    }

    /**
     * 获取选中项在列表中的下标
     */
    public int getSelectedItemPosition() {
        if (adapter != null && selectedItem != null) {
            return adapter.getPosition(selectedItem);
        }
        return -1;
    }

    /**
     * 展示搜索下拉框
     */
    private void showPopup() {
        if (popupWindow != null && popupWindow.isShowing()) return;

        View popupView = LayoutInflater.from(context).inflate(R.layout.spinner_searchable, null);
        EditText editSearch = popupView.findViewById(R.id.edit_search);
        ListView listView = popupView.findViewById(R.id.list_view);

        ArrayAdapter<String> filteredAdapter = new ArrayAdapter<>(context,
                android.R.layout.simple_list_item_1, new ArrayList<>(itemList));
        listView.setAdapter(filteredAdapter);

        popupWindow = new PopupWindow(popupView,
                getWidth(),
                ViewGroup.LayoutParams.WRAP_CONTENT,
                true);
        popupWindow.setBackgroundDrawable(new ColorDrawable(Color.WHITE));
        popupWindow.setElevation(10);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setFocusable(true);

        // 过滤逻辑
        editSearch.addTextChangedListener(new TextWatcher() {
            @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
            @Override public void onTextChanged(CharSequence s, int start, int before, int count) {
                filteredAdapter.getFilter().filter(s);
            }
            @Override public void afterTextChanged(Editable s) {}
        });

        listView.setOnItemClickListener((parent, view, position, id) -> {
            selectedItem = filteredAdapter.getItem(position);
            setText(selectedItem);
            if (listener != null) listener.onItemSelected(selectedItem);
            popupWindow.dismiss();
        });

        popupWindow.showAsDropDown(this, 0, 0, Gravity.START);
    }
}
